//
//  XS_DownloadVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/15.
//

import UIKit

class XS_DownloadVC: XS_BaseVC {
    
    lazy var doneDataArray : [XS_DownloadModel] = []
    lazy var downloadingDataArray : [XS_DownloadModel] = []
    
    var finalDownloadingDataArray : [XS_DownloadModel] = []

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        title = "下载课程"
        tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: .bottomHeight, right: 0)
        tableView.register(UINib.init(nibName: "XS_DownloadListCell", bundle: Bundle.main), forCellReuseIdentifier: "XS_DownloadListCell")
        tableView.delegate = self
        tableView.dataSource = self
        
        let footerView = Bundle.main.loadNibNamed("XS_DownloadFooterView", owner: nil, options: nil)?.last as! XS_DownloadFooterView
        reloadFooterView(footerView: footerView)
        tableView.tableFooterView = footerView
    }
    
    func reloadFooterView(footerView : XS_DownloadFooterView){
        let filePath = XS_DownloadManager_CourseFilePath
        let fileSize = filePath.getFileSize()
        let freeSize = XS_DownloadManager.shared.getSystemFreeSize()
        footerView.titleLabel.text = String.init(format: "已下载课件%ldM ,可用空间%ldG", fileSize/1024/1024,freeSize/1024/1024/1024)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        reloadLocalData()
        NotificationCenter.default.addObserver(self, selector: #selector(updateDownloadingQueue), name: NSNotification.Name.init(.downloadingQueueUpdateNotification), object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.init(.downloadingQueueUpdateNotification), object: nil)
    }
    
    @objc func updateDownloadingQueue(){
        reloadLocalData()
        downloadingDataArray = XS_DownloadManager.shared.downloadQueue;
        reloadFooterView(footerView: tableView.tableFooterView as! XS_DownloadFooterView)
        tableView.reloadData()
    }
    
    func reloadLocalData(){
        let dataArray = XS_DownloadManager.shared.getModels()
        doneDataArray = dataArray
        downloadingDataArray = XS_DownloadManager.shared.downloadQueue;
        
        if isOpenResumeDownload {
            let storageQueue = UserDefaults.standard.value(forKey: XS_DownloadManager_Queue_SaveKey)
            if storageQueue != nil {
                let storageQueueArray = storageQueue as! [String]
                if storageQueueArray.count > 0 {
                    for json in storageQueueArray {
                        let downloadModel = XS_DownloadModel.deserialize(from: json)
                        downloadingDataArray.append(downloadModel!)
                    }
                }
            }
        }
        
        
        finalDownloadingDataArray.removeAll()
        
        var lastModel = XS_DownloadModel()
        for model in downloadingDataArray {
            if model.curriculumModel.id == lastModel.curriculumModel.id {
                if model.hourModel.id == lastModel.hourModel.id {
                    //同一章节
                    var newIndex = 0
                    for index in 0...model.hourModel.curriculumHourDtoList.count - 1 {
                        let subModel = model.hourModel.curriculumHourDtoList[index]
                        if subModel.id == lastModel.listModel.id {
                            newIndex = index
                        }
                    }
                    model.hourModel.curriculumHourDtoList[newIndex] = lastModel.listModel
                }else{
                    //不同章节
                    //如果添加过了就别重复添加了
                    var ret = true
                    for lastSubModel in lastModel.hourModels {
                        for originSubModel in model.hourModels {
                            if lastSubModel.id == originSubModel.id {
                                ret = false
                                break
                            }
                        }
                    }
                    if ret {
                        model.hourModels = model.hourModels + lastModel.hourModels;
                    }
                }
            }else{
                finalDownloadingDataArray.append(model)
            }
            lastModel = model
        }
        tableView.reloadData()
    }

}

extension XS_DownloadVC : UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return doneDataArray.count
        }
        return finalDownloadingDataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XS_DownloadListCell", for: indexPath) as! XS_DownloadListCell
        if indexPath.section == 0 {
            cell.model = doneDataArray[indexPath.item]
        }else{
            cell.model = finalDownloadingDataArray[indexPath.item]
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 104
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 8
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        if section == 1 {
//            let view = Bundle.main.loadNibNamed("XS_DownloadFooterView", owner: nil, options: nil)?.last as! XS_DownloadFooterView
//            let filePath = XS_DownloadManager_CourseFilePath
//            let fileSize = filePath.getFileSize()
//            let freeSize = XS_DownloadManager.shared.getSystemFreeSize()
//            view.titleLabel.text = String.init(format: "已下载课件%ldM ,可用空间%ldG", fileSize/1024/1024,freeSize/1024/1024/1024)
//            return view
//        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 32
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = Bundle.main.loadNibNamed("XS_DownloadHeaderView", owner: nil, options: nil)?.last as! XS_DownloadHeaderView
        view.statusLabel.text = section == 0 ? "已完成" : "下载中"
        return view
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var downloadModel = XS_DownloadModel()
        if indexPath.section == 0 {
            downloadModel = doneDataArray[indexPath.item]
            let startVC = XS_DownloadStartVC()
            startVC.downloadModel = downloadModel
            startVC.title = downloadModel.curriculumModel.curriculumName
            navigationController?.pushViewController(startVC, animated: true)
        }else{
            downloadModel = finalDownloadingDataArray[indexPath.item]
            let downloadingVC = XS_DownloadingVC()
            downloadingVC.model = downloadModel
            navigationController?.pushViewController(downloadingVC, animated: true)
        }
        
    }
}

